package com.newasia.server.common.builder;

import com.alibaba.fastjson.JSONObject;
import com.newasia.server.dal.entitys.WxLogin;
import lombok.Data;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class WeChatInfoApiBuilder {

    private UserInfoParam infoParam = new UserInfoParam();

    public WeChatInfoApiBuilder addToken(String token) {
        infoParam.setAccessToken(token);
        return this;
    }

    public WeChatInfoApiBuilder addOpenId(String openId) {
        infoParam.setOpenId(openId);
        return this;
    }

    public UserInfoParam build() {
        return this.infoParam;
    }

    public WxLogin getUserInfo(UserInfoParam infoParam){
        WxLogin wxLogin = new WxLogin();
        String url = "https://api.weixin.qq.com/sns/userinfo?"
                + "access_token="+ infoParam.accessToken
                + "&openid="+ infoParam.openId;
        StringBuilder json = new StringBuilder();
        try {
            URL urlObject = new URL(url);
            URLConnection uc = urlObject.openConnection();
            uc.setRequestProperty("contentType", "UTF-8");
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"utf-8"));
            String inputLine = null;

            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
            wxLogin = JSONObject.parseObject(json.toString(),WxLogin.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wxLogin;
    }

    @Data
    public class UserInfoParam {
        private String accessToken;
        private String openId;
    }
}
